TARGET	:= $(shell basename $(CURDIR))
BUILD	:= build
INCLS	:= include psdlite build
SOURCES	:= src psdlite

ARCH	:= 
CC	:= $(ARCH)gcc
CXX     := $(ARCH)g++
CFLAGS	:= -O2 -Wall $(INCLUDE)

ifneq ($(notdir $(CURDIR)), $(BUILD))

export INCLUDE	:= $(foreach dir, $(INCLS) $(BUILD), -I$(CURDIR)/$(dir))
export OUTPUT	:= $(CURDIR)/$(TARGET)
export VPATH	:= $(foreach dir, $(SOURCES), $(CURDIR)/$(dir))

CFILES   := $(foreach dir, $(SOURCES), $(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir, $(SOURCES), $(notdir $(wildcard $(dir)/*.cpp)))

export OFILES := $(CFILES:.c=.o) $(CPPFILES:.cpp=.o)

.PHONY: $(BUILD) clean

$(BUILD):
	@[ -d $@ ] || mkdir -p $@
	@make --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile

clean:
	@echo clean ... $(TARGET)
	@rm -fr $(BUILD) $(TARGET)

else

DEPENDS := $(OFILES:.o=.d)


$(OUTPUT): $(OFILES)
	@$(CXX) -lm $^ -o $@

%.o : %.c
	@echo $(notdir $<)
	@$(CC) -MM $(CFLAGS) -o $*.d $<
	@$(CC) $(CFLAGS) -c $< -o$@

%.o : %.cpp
	@echo $(notdir $<)
	@$(CXX) -MM $(CFLAGS) -o $*.d $<
	@$(CXX) $(CFLAGS) -c $< -o$@

-include $(DEPENDS)

endif
